package pers.dawnyang.config.security;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author dawn
 * @date 2020/12/14
 */
// @Order(1)
// @Component
// @WebFilter({"/*"})
@Slf4j
public class DecodeFilter2 extends OncePerRequestFilter {

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain chain) throws ServletException, IOException {
    String contentType = request.getContentType();
    String url = request.getRequestURI();
    // 判断是否是json形式请求
    if (StringUtils.isNotBlank(contentType) && contentType.contains("application/json")) {
      String requestBody = getRequestBody((HttpServletRequest) request);
      JSONObject jsonObject = JSONObject.parseObject(requestBody);
      if (jsonObject != null && StringUtils.isNotBlank(jsonObject.getString("enc"))) {
        String encStr = jsonObject.getString("enc");
        String decStr = new String(Base64.getDecoder().decode(encStr), "utf-8");
        WrapperedRequest wrapRequest = new WrapperedRequest((HttpServletRequest) request, decStr);
        WrapperedResponse wrapResponse = new WrapperedResponse((HttpServletResponse) response);
        chain.doFilter(wrapRequest, wrapResponse);
        byte[] data = wrapResponse.getResponseData();
        log.info("原始返回数据： " + new String(data, "utf-8"));
        // 加密返回报文
        String responseBodyMw = Base64.getEncoder().encodeToString(data);
        Map<String, Object> encRes = new HashMap<>();
        encRes.put("enc", responseBodyMw);
        String encResStr = JSONObject.toJSONString(encRes);
        log.info("加密返回数据： " + encResStr);
        writeResponse(response, encResStr);
      }
    } else {
      Map<String, String[]> parameterMap = request.getParameterMap();



      chain.doFilter(request, response);
    }
  }

  private String getRequestBody(HttpServletRequest req) {
    try {
      BufferedReader reader = req.getReader();
      StringBuffer sb = new StringBuffer();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line);
      }
      String json = sb.toString();
      return json;
    } catch (IOException e) {
      log.info("请求体读取失败" + e.getMessage());
    }
    return "";
  }

  private void writeResponse(ServletResponse response, String responseString) throws IOException {
    PrintWriter out = response.getWriter();
    out.print(responseString);
    out.flush();
    out.close();
  }
}
